<template>
  <div class="legal-review-container">
    <HeaderIndex title="广告智审" />
    <div class="form-info">
      <div class="form-info-switch">
        <span
          :class="{ 'switch-active': item.isActive }"
          v-for="(item, index) in switchBtnTextArr"
          :key="index"
          @click="handleSwitchBtn(item.name, index)"
          >{{ item.name }}</span
        >
      </div>
      <div class="form-info-list">
        <div class="form-info-item targeting-issues">
          <span>业务类型</span>
          <span>
            <van-dropdown-menu active-color="#429df8">
              <van-dropdown-item
                :title="examinationObj.trade"
                v-model="examinationObj.trade"
                :options="businessType"
              />
            </van-dropdown-menu>
          </span>
        </div>
        <div class="form-info-item targeting-issues">
          <span>发布渠道</span>
          <span
            ><van-dropdown-menu active-color="#429df8">
              <van-dropdown-item
                :title="examinationObj.region"
                v-model="examinationObj.region"
                :options="releaseChannel"
              /> </van-dropdown-menu
          ></span>
        </div>
        <div
          class="form-info-item detect-text"
          v-show="switchBtnTextArr[0].isActive"
        >
          <span>检测文本<span class="required-active">*</span></span>
          <span>
            <textarea
              v-model="detectText"
              placeholder="请输入检测文本"
            ></textarea>
            <span class="detect-text-length"
              >{{ detectText.length }}/{{ detectTextLen }}</span
            >
          </span>
        </div>
        <div
          class="form-info-item add-image"
          v-show="switchBtnTextArr[1].isActive"
        >
          <span>添加图片<span class="required-active">*</span></span>
          <span class="form-uploader">
            <van-uploader
              v-model="fileList"
              :max-size="8000 * 1024"
              :max-count="10"
              :multiple="true"
              :before-read="handleBeforeRead"
              :after-read="handleAfterRead"
              @oversize="handleOversize"
              @delete="handleImageDelete"
            >
              <div class="custom-add-picture-style">
                <img src="../../assets/images/pic.png" alt="" />
                <p>添加图片</p>
              </div>
            </van-uploader>
          </span>
          <p>支持jpg、jpeg、png、bmp，单张图最大支持8MB</p>
        </div>
      </div>
      <van-button
        class="submit"
        :loading="loading"
        type="info"
        text="开始审查"
        loading-text="加载中..."
        :disabled="disabledVal"
        @click="handleSubmit"
      />
    </div>
  </div>
</template>

<script>
import HeaderIndex from "@/components/header";
import { textReview, readTextFromImg } from "@/api";
import { Toast } from "@/utils";
export default {
  name: "LegalReview",
  components: {
    HeaderIndex,
  },
  data() {
    return {
      switchName: "文字审核", //切换的名称
      //切换按钮文字数组
      switchBtnTextArr: [
        {
          name: "文字审核",
          isActive: true,
        },
        {
          name: "图片审核",
          isActive: false,
        },
      ],
      businessType: [
        //业务类型
        { text: "请选择", value: "" },
        { text: "融合类", value: "融合类" },
        { text: "流量类", value: "流量类" },
        { text: "终端类", value: "终端类" },
        { text: "宽带类", value: "宽带类" },
        { text: "套餐类", value: "套餐类" },
        { text: "话费类", value: "话费类" },
        { text: "靓号类", value: "靓号类" },
      ],
      releaseChannel: [
        //发布渠道
        { text: "请选择", value: "" },
        { text: "手机营业app", value: "手机营业app" },
        { text: "微信公众号", value: "微信公众号" },
        { text: "网上营业厅", value: "网上营业厅" },
        { text: "线下营业厅", value: "线下营业厅" },
        { text: "电台广播", value: "电台广播" },
        { text: "短信", value: "短信" },
        { text: "其它", value: "其它" },
      ],
      fileList: [], //存储文件
      fileConList: [], //存储文件文字
      detectText: "", //检测文本
      detectTextLen: 2000, //检测文本长度
      examinationObj: {
        trade: "", //业务类型
        region: "", //发布渠道
        content: "", //检测文本
      },
      loading: false, //提交按钮是否显示加载中效果
      disabledVal: false, //是否禁用按钮
      imgTypeArr: ["image/jpg", "image/bmp", "image/png", "image/jpeg"], //支持的上传图片类型
    };
  },
  //组件路由守卫，处理从首页进入法律审核页面不需要缓存
  beforeRouteEnter(to, from, next) {
    if (from.name == "Home") {
      next((vm) => {
        vm.handleSwitchBtn("文字审核", 0);
        vm.examinationObj.trade = "";
        vm.examinationObj.region = "";
        vm.detectText = "";
        vm.fileList = [];
      });
    } else {
      next();
    }
  },
  watch: {
    //监听检测文本长度
    detectText(newVal) {
      if (newVal.length > this.detectTextLen) {
        Toast.fail(`内容长度不能大于${this.detectTextLen}`);
      }
    },
  },
  methods: {
    /**
     * 切换按钮
     * @param {*} name 切换的名称
     * @param {*} index 下标
     */
    handleSwitchBtn(name, index) {
      //赋值
      this.switchName = name;
      this.switchBtnTextArr.forEach((item, i) => {
        item.isActive = index == i;
      });
    },

    /**
     * 获取新的文件对象，多个上传的文件处理
     * @param {*} file 文件
     */
    getNewFiles(file) {
      return Array.isArray(file) ? [...file] : [file];
    },

    /**
     * 图片类型检查
     * @param {*} file 文件
     */
    checkFile(file) {
      const isIncludeFormat = this.imgTypeArr.includes(file.type);
      !isIncludeFormat && Toast.fail("选择的图片中包含不支持的格式");
      return isIncludeFormat;
    },

    /**
     * 文件上传之前的检验，判断图片类型
     * @param {*} file 文件
     */
    handleBeforeRead(file) {
      return this.getNewFiles(file)
        .map((f) => {
          return this.checkFile(f);
        })
        .every((e) => e);
    },

    /**
     * 文件读取完成后的回调函数
     * @param {*} file 文件
     */
    handleAfterRead(file) {
      this.getNewFiles(file).forEach((f) => {
        f.status = "uploading";
        f.message = "上传中...";
        this.getImageText(f);
      });
    },

    /**
     * 文件大小超过限制时触发，提示信息
     */
    handleOversize() {
      Toast.fail("支持jpg、jpeg、png、bmp，单张图最大支持8MB.");
    },

    /**
     * 删除图片信息
     */
    handleImageDelete({ file }) {
      //找到要删除的下标
      const index = this.fileConList.findIndex(
        (item) => item.name == file.name
      );

      //删除
      index != -1 && this.fileConList.splice(index, 1);
    },

    /**
     * 获取图片文字
     * @param {*} files 文件
     */
    async getImageText(files) {
      //上传图片时禁用按钮
      this.disabledVal = true;

      //发送请求
      const formData = new FormData();
      formData.append("file", files.file);
      const data = await readTextFromImg(formData);

      if (data) {
        files.status = "done";
        files.message = "上传成功";

        //存储数据
        this.fileConList.push({
          text: data,
          name: files.file.name,
        });
      } else {
        files.status = "failed";
        files.message = "上传失败";

        Toast.fail("文字识别出错");

        //删除上传失败的图片
        this.fileList = this.fileList.filter((f) => f.status !== "failed");
      }

      //上传完毕后解除按钮
      this.disabledVal = false;
    },

    /**
     * 删除数字数组中重复的关键字
     * @param {*} propNum 数字关键字
     * @param {*} direction 方向 start或end
     */
    removePropNumDuplicates(propNum, direction) {
      const map = new Map();

      for (let i = 0; i < propNum.length; i++) {
        const { start, end } = propNum[i];
        const newDirection = direction === "start" ? start : end;
        map.set(newDirection, propNum[i]);
      }

      const resultArr = [];
      map.forEach((v) => {
        resultArr.push(v);
      });

      return resultArr;
    },

    /**
     * 删除重复项
     * @param {*} propNum 数字关键字
     */
    removeDuplicates(propNum) {
      propNum = this.removePropNumDuplicates(propNum, "start");
      propNum = this.removePropNumDuplicates(propNum, "end");
      return propNum;
    },

    /**
     * 开始审查
     */
    async handleSubmit() {
      const isTextReview = this.switchName == "文字审核";
      const isImageReview = this.switchName == "图片审核";

      //校验
      if (isTextReview && !this.detectText) {
        Toast.fail("请输入广告审核内容");
      } else if (isTextReview && this.detectText.length > this.detectTextLen) {
        Toast.fail(`内容长度不能大于${this.detectTextLen}`);
      } else if (isImageReview && !this.fileList.length) {
        Toast.fail("请选择广告审核内容的图片");
      } else {
        //文字直接赋值，如果是图片返回的文字，可能会有多个，需要特殊处理
        this.examinationObj.content = isImageReview
          ? this.fileConList.map((item) => item.text).join("")
          : this.detectText;

        try {
          //按钮状态处理
          this.loading = true;

          //请求
          const { disable, risk, prop, propNum = [], regulation } =
            (await textReview(this.examinationObj)) || {};

          //提示信息
          Toast.customToast({
            type: "success",
            message: "提交成功",
            onClose: () => {
              //跳转到审核页面
              const pageData = {
                ...this.examinationObj,
                disable,
                risk,
                prop,
                propNum: this.removeDuplicates(propNum),
                regulation
              }
              localStorage.setItem('resultData', JSON.stringify(pageData))
              this.$router.push({
                name: "ExamineResult",
              });
            },
          });
        } finally {
          //按钮状态处理
          this.loading = false;
        }
      }
    },
  },
};
</script>

<style lang="less">
@import url("~@/assets/styles/resetComponentStyle.less");
</style>
<style lang="less" scoped>
@import url("~@/assets/styles/legalReview/index.less");
</style>